package com.hbnu.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author kittychen
 * @since 2025-10-27 19:07
 */
public class Ticket implements Runnable {

    private static final Lock lock = new ReentrantLock();  // 创建锁
    private int ticket = 30;

    @Override
    public /* synchronized */ void run() {
        while (true) {
            lock.lock(); // 加🔒
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第" + ticket + "号票");
                ticket--;
            } else {

                break;
            }
            lock.unlock(); // 解锁
            // synchronized (this) {
            //     if (ticket > 0) {
            //         System.out.println(Thread.currentThread().getName() + "卖出第" + ticket + "号票");
            //         ticket--;
            //     } else
            //         break;
            // }
        }
    }
}
